const express = require('express');
const router = express.Router();
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const co = require('co');

const DB = require('../db');
const DT = require('../lib/dt');
const EJS = require('../lib/ejs');

router.get('/', function (req, res, next) {
    co(function* () {
        const id = req.query.id || 70;
        const me = yield DB.Person.findByPk(id, {raw: true});
        const tree = ['<ul>'];
        if (me) {
            yield putTree(tree, me, 5);
        }
        tree.push('</ul');
        const data = tree.join('\r\n');
        res.render('tree', {id: id, data: data});
    }).catch((err) => {
        next(err)
    })
});

// 把人变成ul放到树里
function putTree(tree, me, deep) {
    return function (cb) {
        if (deep-- <= 0) {
            cb();
            return;
        }
        co(function* () {
            tree.push('<li>');
            if (me.xid > 0) {
                // 爱人
                const ar = yield DB.Person.findByPk(me.xid, {raw: true});
                tree.push(`<a><b>${me.name}</b> ${ar.name}</a>`);
                // 我的孩子
                const hz = me.sex === 'M' ? yield DB.Person.findAll({
                    raw: true,
                    where: {fid: me.id,},
                    order: ['nong'],
                }) : yield DB.Person.findAll({
                    raw: true,
                    where: {mid: me.id,},
                    order: ['nong'],
                });
                if (hz.length > 0) {
                    tree.push('<ul>');
                    for (let i = 0; i < hz.length; i++) {
                        yield putTree(tree, hz[i], deep);
                    }
                    tree.push('</ul>');
                }
            } else {
                tree.push(`<a><b>${me.name}</b> </a>`)
            }
            tree.push('</li>');
            cb();
        }).catch((err) => {
            cb(err);
        })
    }
}

module.exports = router;